package com.moli.iov.admin.web.controller;


import com.moli.iov.admin.constants.Constants;
import com.moli.iov.admin.model.vo.req.BaseVo;
import com.moli.iov.admin.model.vo.req.RealtimeMessageDownloadVo;
import com.moli.iov.admin.model.vo.req.RealtimeMessageQueryVo;
import com.moli.iov.his.dto.RealtimeMessageDTO;
import com.moli.iov.his.model.dto.StatOnlineReportDTO;
import com.moli.iov.his.model.dto.StatOnlineReqDTO;
import com.moli.iov.his.remote.IHisStatRemoteService;
import com.moli.iov.his.remote.RealtimeMessageRemoteService;
import com.moli.iov.model.dto.req.PageExtend;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.util.DateUtil;
import com.moli.iov.util.ExcelUtil;
import com.moli.iov.util.HttpUtil;
import com.moli.iov.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static org.springframework.http.HttpHeaders.*;

/**
 *
 * Query for all real time report message.
 *
 * <p>
 * Contain:
 *  According to vehicle shelf and pick up data information for query all real time report message.
 *  Download to a original real time report message.
 * Through {@link ExcelUtil} to Export for selection a original real time report message.
 *
 * @author OAK
 * @version 3.0.1
 * @since 2019/12/10 15:52 PM.
 */
@Slf4j
@RestController
public class RealtimeMessageController extends BaseController{

    @Reference(group = "${service.group}", check = false)
    private RealtimeMessageRemoteService realtimeMessageRemoteService;

    @PostMapping("/realTimeMessage/getRealtimeMessages")
    public RestResponse<PageExtend<RealtimeMessageDTO>> queryRealtimeMessageByRealtimeMessageQueryVo(@RequestBody RealtimeMessageQueryVo realtimeMessageQueryVo) {
        try{
            String vin = realtimeMessageQueryVo.getVin();
            Date beginTime = realtimeMessageQueryVo.getBeginTime(),
                    endTime = realtimeMessageQueryVo.getEndTime();
            Long pageSize = realtimeMessageQueryVo.getPageSize(),
                    pageNum = realtimeMessageQueryVo.getPageNum();

            RestResponse<PageExtend<RealtimeMessageDTO>> realtimeMessageDTOList =
                    realtimeMessageRemoteService.queryRealtimeMessageByVinAndStartTimeAndEndTime(vin, beginTime, endTime, pageNum, pageSize);
            return realtimeMessageDTOList;
        }catch (Exception e){
            return RestResponse.failure("接口查询异常");
        }
    }

    @PostMapping("/realTimeMessage/exports")
    public void exports(@RequestBody RealtimeMessageQueryVo realtimeMessageQueryVo,
                        HttpServletRequest req, HttpServletResponse res) throws Exception {

        Long pageSize = realtimeMessageQueryVo.getPageSize(),
                pageNum = realtimeMessageQueryVo.getPageNum();

        if(pageSize == null || pageSize == null){
            realtimeMessageQueryVo.setPageNum(Constants.EXPORT_PAGE_NUM);
            realtimeMessageQueryVo.setPageSize(Constants.EXPORT_PAGE_SIZE);
        }

        String vin = realtimeMessageQueryVo.getVin();
        Date beginTime = realtimeMessageQueryVo.getBeginTime(),
                endTime = realtimeMessageQueryVo.getEndTime();

        RestResponse<PageExtend<RealtimeMessageDTO>> restResponse =
                realtimeMessageRemoteService.queryRealtimeMessageByVinAndStartTimeAndEndTime(vin, beginTime, endTime, pageNum, pageSize);
        List<RealtimeMessageDTO> realtimeMessageDTOList = new ArrayList<>();
        if(restResponse.flag){
            realtimeMessageDTOList = restResponse.getData().getRecords();
        }
        if(realtimeMessageDTOList != null){
            final String[] propNames = {"vin", "vehicleStatus","speed", "soc","powerGear","leasingModel",
                    "powerStatus", "keyStatus","totalVoltage","location","odometer","collectTime"};
            final String[] headStrs = {"车架号","车辆状态","车速","SOC","电源档位", "租赁模式","动力状态","钥匙状态", "蓄电池电压", "经纬度信息", "仪表里程", "数据采集时间"};
            String title = "报文信息";
            ExcelUtil.exportDataExcel(req, res, realtimeMessageDTOList, propNames, headStrs, title);
        }
    }


    @PostMapping("/realTimeMessage/export")
    public void export(@RequestBody RealtimeMessageQueryVo realtimeMessageQueryVo,
                        HttpServletRequest req, HttpServletResponse res) throws Exception {

        Long pageSize = realtimeMessageQueryVo.getPageSize(),
                pageNum = realtimeMessageQueryVo.getPageNum();

        if(pageSize == null || pageSize == null){
            realtimeMessageQueryVo.setPageNum(Constants.EXPORT_PAGE_NUM);
            realtimeMessageQueryVo.setPageSize(Constants.EXPORT_PAGE_SIZE);
        }

        String vin = realtimeMessageQueryVo.getVin();
        Date beginTime = realtimeMessageQueryVo.getBeginTime(),
                endTime = realtimeMessageQueryVo.getEndTime();

        RestResponse<PageExtend<RealtimeMessageDTO>> restResponse =
                realtimeMessageRemoteService.queryRealtimeMessageByVinAndStartTimeAndEndTime(vin, beginTime, endTime, pageNum, pageSize);
        List<RealtimeMessageDTO> realtimeMessageDTOList = new ArrayList<>();
        if(restResponse.flag){
            realtimeMessageDTOList = restResponse.getData().getRecords();
        }
        if(realtimeMessageDTOList != null){
            final String[] propNames = {"vin", "vehicleStatus","speed", "soc","powerGear","leasingModel",
                    "powerStatus", "keyStatus","totalVoltage","location","odometer","collectTime"};
            final String[] headStrs = {"车架号","车辆状态","车速","SOC","电源档位", "租赁模式","动力状态","钥匙状态", "蓄电池电压", "经纬度信息", "仪表里程", "数据采集时间"};
            String title = "报文信息";
            ExcelUtil.exportDataExcel(req, res, realtimeMessageDTOList, propNames, headStrs, title);
        }
    }

    @Deprecated
    @PostMapping("/realTimeMessage/download")
    public void download(@RequestBody RealtimeMessageDownloadVo realtimeMessageDownloadVo,
                                                      HttpServletRequest req, HttpServletResponse res) throws Exception {
        String fileName = "原始报文信息";
        boolean isMSIE = HttpUtil.isMSBrowser(req);
        if (isMSIE) {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        } else {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        String rowKey = realtimeMessageDownloadVo.getRowKey();
        if(StringUtil.isNotBlank(rowKey)){
            RestResponse<String> restResponse = realtimeMessageRemoteService.queryRealtimeMessageByRowKey(rowKey);
            if(restResponse.flag){
                res.reset();
                setHeaders(res);

                res.setHeader(CONTENT_DISPOSITION, String.format("attachment; filename=\"%s\".txt", fileName));
                try (BufferedOutputStream  outputStream = new BufferedOutputStream(res.getOutputStream()))
                {
                    res.setContentType("application/octet-stream");
                    outputStream.write(restResponse.getData().getBytes("UTF-8"));
                    outputStream.flush();
                }
            }
        }
    }
}
